<template>
  <div id="home">
    <div v-if="!showLoading">
      <Header />
      <!-- 轮播图 -->
      <Sowing :sowing_list="sowing_list" />
      <!-- 中部导航 -->
      <Nav :nav_list="nav_list" />
      <!-- 秒杀 -->
      <FlashSale :flashsale_list="flashsale_list" />
      <!-- 猜你喜欢 -->
      <YouLike :YouLike_list="YouLike_list" />
      <!-- 返回顶部 -->
      <ToTop :scrollToTop="scrollToTop" v-show="showBackStatus" />
    </div>
    <van-loading
      v-else
      type="spinner"
      color="#75a342"
      style="position: absolute;left:50%;top: 40%;transform: translate(-50%)"
    >加载中…</van-loading>
  </div>
</template>


<script>
// 1. 引入数据
import { getHomeData } from "./../../service/api/index";

//2. 引入组件
// 首页
import Header from "./components/header/Header";
// 轮播图
import Sowing from "./components/sowing/Sowing";
// nav
import Nav from "./components/nav/Nav";
// 限时抢购
import FlashSale from "./components/flashSale/FlashSale";
// 猜你喜欢
import YouLike from "./components/youlike/YouLike";
// 回到顶部
import ToTop from "./components/toTop/ToTop";

// 3. 引入处理返回顶部徐函数
import { showBack, animate } from "@/config/global";

//4. 引入消息订阅插件
import PubSub from "pubsub-js";
// 提示插件
import { Toast } from "vant";

//5. 引入vuex
import { mapMutations, mapState } from "vuex";

//6. 引入接口
import { addGoodsToCart } from "./../../service/api/index";

export default {
  name: "home",
  data() {
    return {
      // 首页的轮播图数据
      sowing_list: [],
      // 导航数据
      nav_list: [],
      //限时抢购
      flashsale_list: [],
      //猜你喜欢
      YouLike_list: [],
      // 是否显示加载图标
      showLoading: true,
      // 是否显示返回顶部的按钮
      showBackStatus: false
    };
  },
  created() {
    // 2. 请求网络数据
    this.reqData();
    /*
    getHomeData()
      .then(response => {
        console.log(response);
        if (response.success) {
          this.sowing_list = response.data.list[0].icon_list;
          this.nav_list = response.data.list[2].icon_list;
          this.flashsale_list = response.data.list[3].product_list;
          this.YouLike_list = response.data.list[12].product_list;

          // 隐藏加载动画
          // this.showLoading = false;
          // 开始监听滚动, 到达一定位置就显示返回顶部按钮
          showBack(status => {
            // console.log(status);
            this.showBackStatus = status;
          });
        }
      })
      .catch(error => {
        // //todo..
        // console.log(error);
      });

    */
  },
  computed: {
    ...mapState(["userInfo"])
  },
  mounted() {
    // 订阅消息(添加到购物车的消息)
    PubSub.subscribe("homeAddToCart", (msg, goods) => {
      if (msg === "homeAddToCart") {
        // 判断用户是否登录
        if (this.userInfo.token) {
          //已经登录
          //添加到服务器购物车
          this.dealGoodsAdd(goods);

          /*  添加到本地购物车
          this.ADD_GOODS({
            goodsId: goods.id,
            goodsName: goods.name,
            smallImage: goods.small_image,
            goodsPrice: goods.price
          });
          // 提示用户
          Toast({
            message: "添加购物车成功!",
            duration: 800
          });
          */
        } else {
          // 没有登录
          this.$router.push("/login");
        }
      }
    });
  },
  components: {
    Header,
    Sowing,
    Nav,
    FlashSale,
    YouLike,
    ToTop
  },
  methods: {
    ...mapMutations(["ADD_GOODS"]),
    async reqData() {
      let res = await getHomeData();
      // console.log(res);
      if (res.success) {
        this.sowing_list = res.data.list[0].icon_list;
        this.nav_list = res.data.list[2].icon_list;
        this.flashsale_list = res.data.list[3].product_list;
        this.YouLike_list = res.data.list[12].product_list;

        // 隐藏加载动画
        this.showLoading = false;
        // 开始监听滚动, 到达一定位置就显示返回顶部按钮
        showBack(status => {
          // console.log(status);
          this.showBackStatus = status;
        });
      }
    },
    // 1. 滚回顶部
    scrollToTop() {
      // 做缓动动画返回顶部
      let docB = document.documentElement || document.body;
      animate(docB, { scrollTop: "0" }, 400, "ease-out");
    },
    //2. 添加商品到购物车
    //添加到服务器(异步 async)
    async dealGoodsAdd(goods) {
      //2.1 调用服务器端的接口
      let result = await addGoodsToCart(
        this.userInfo.token,
        goods.id,
        goods.name,
        goods.price,
        goods.small_image
      );
    
      // console.log(result);
      //添加到本地
      if (result.success_code === 200) {
        this.ADD_GOODS({
          goodsId: goods.id,
          goodsName: goods.name,
          smallImage: goods.small_image,
          goodsPrice: goods.price
        });
        // 提示用户
        Toast({
          message: "添加购物车成功!",
          duration: 800
        });
      }
    }
  },

  beforeDestroy() {
    //使用订阅要设置取消,不然会有BUG
    PubSub.unsubscribe("homeAddToCart");
  }
};
</script>


<style lang='less' scoped>
#home {
  width: 100%;
  height: 3000px;
  background-color: #f5f5f5;
}
</style>